import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Test03 {
    public static int maxFrequencyWithSlidingWindow(int[] nums, int k) {
        int maxLen = 0;
        Map<Integer, Integer> count = new HashMap<>();
        int left = 0;

        for (int right = 0; right < nums.length; right++) {
            int num = nums[right];
            count.put(num, count.getOrDefault(num, 0) + 1);

            // 当前窗口内可以替换的数量
            int finalLeft = left;
            int finalRight = right;
            int replaceable = (int) count.entrySet().stream()
                    .filter(entry -> entry.getValue() > 1)
                    .mapToInt(entry -> Math.min(entry.getValue() - 1, k + finalLeft - finalRight + 1 - (entry.getKey() == num ? 1 : 0)))
                    .sum();

            while (right - left + 1 - replaceable > k) {
                count.put(nums[left], count.get(nums[left]) - 1);
                if (count.get(nums[left]) == 1 && count.get(nums[left]) > 0) {
                    count.remove(nums[left]);
                }
                left++;
            }

            maxLen = Math.max(maxLen, right - left + 1);
        }

        return maxLen;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the elements of the array separated by spaces:");
        String input = scanner.nextLine();
        String[] numStrings = input.split("\\s+");
        int[] nums = new int[numStrings.length];
        for (int i = 0; i < numStrings.length; i++) {
            nums[i] = Integer.parseInt(numStrings[i]);
        }
        System.out.println("Enter the number of allowed replacements (k):");
        int k = scanner.nextInt();
        System.out.println("The maximum length of the equal subsequence is: " + maxFrequencyWithSlidingWindow(nums, k));
        scanner.close();
    }
}
